Function as Input Parameter
//===========================================================================================================
// FUNCTION: executeFunction
//===========================================================================================================
fun executeFunction( receivedFunction: (name: String, age: Int) -> String ) {
var result = receivedFunction("John", 20)
println(result)
}
//===========================================================================================================
// FUNCTION: main
//===========================================================================================================
fun main() {
//DECLARE LOCAL VARIABLE
var weight = 150 //It is sent as Closure Property
//DECLARE FUNCTIONS.
fun namedFunction (name: String, age: Int) : String { return("$name is $age years old and $weight kg.")
}
var anonymFunc = fun (name: String, age: Int) : String { return("$name is $age years old and $weight kg.")
}
var lambdaFunc = { name: String, age: Int -> "$name is $age years old and $weight kg"
}
//USE FUNCTIONS AS PARAMETER (Sends Closure With Weight Property).
executeFunction(::namedFunction) //Function Name
executeFunction(anonymFunc) //Variable Name
executeFunction(lambdaFunc) //Variable Name
executeFunction( fun (name: String, age: Int) : String { return("$name is $age years old and $weight kg")
})
executeFunction( { name: String, age: Int -> "$name is $age years old and $weight kg" } ) //Lambda
}
Function as Return Value
//===========================================================================================================
//FUNCTION: getFunction
//===========================================================================================================
fun returnFunction ( weight: Int) : (name: String, age: Int) -> String {
return { name: String, age: Int -> "$name is $age years old and $weight kg" }
}
//===========================================================================================================
//FUNCTION: main
//===========================================================================================================
fun main() {
var returnedFunction = returnFunction(150) //Returns Closure with Weight Property already initialized
var result = returnedFunction("John", 20) //Call Function with missing Parameters
println(result)
}